#!/usr/bin/env python
"""Example shows how to identyify neighbours in a graph.
We use a (pointless) complete graph"""

import logging
import sys

import networkx as nx
import nxchaos as nxc

#_______________________________________________________________________________

NODES = 10
nxc.setup_log('debug')
_logger = logging.getLogger('nxchaos.test')

#_______________________________________________________________________________

class IdentifyNeighbours(nxc.algorithm.IAlgorithm):
    neighbours = {} # A dictionary of neighbours
    def run(self):

        for i in range(self.degree):
            self.send(i, self.id)
        yield

        for port, id in self.inbox:
            self.neighbours[port]= id
        self.save_data(self.neighbours)
        _logger.info("{id} neighbours are: {n}".format(id=self.id, n=self.neighbours))
        

#_______________________________________________________________________________

if __name__ == "__main__":

    if len(sys.argv) > 1:
        NODES = int(sys.argv[1])

    gfactory = nxc.graph.GraphFactory()
    graph = gfactory.from_builtin("complete", n=NODES)

    # Creating the graph image (OPTIONAL):
    nxc.util.render_picture(graph, True, True, 'complete.png')
    nxc.util.render_text(graph)


    # Creating the network
    network = nxc.network.Network(graph, IdentifyNeighbours)
    network.save_partial_data(True, './complete_graph.txt')
    network.prepare() # Reseting the network

    # Runing the network
    while network.is_working():
        _logger.info("Round nr {0}".format(network.round_number()))
        network.round()
